package warmachineroster.ui.views;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.Page;

public abstract class RoundupPage extends Page implements IRoundupPage{
	
	public RoundupPage() {
	}

	private Object model;

	private ContentAdapter contentAdapter = new ContentAdapter();
	
	private Composite control;
	
	private class ContentAdapter extends EContentAdapter{

		@Override
		public void notifyChanged(Notification notification) {
			if (notification.getEventType()!= Notification.REMOVING_ADAPTER){
				refreshView();
			}
			super.notifyChanged(notification);
		}
		
	}

	protected abstract void refreshView();
	
	@Override
	public void createControl(Composite parent) {
		control = new Composite(parent, SWT.NONE);
		control.setLayout(new FillLayout(SWT.VERTICAL));
		createPageControl(control);
		refreshView();
	}

	protected abstract void createPageControl(Composite parent) ;

	@Override
	public void setFocus() {
//		getControl().setFocus();
	}
	
	@Override
	public Control getControl() {
		return control;
	}

	protected Object getModel(){
		return model;
	}

	private void hookIntoModel(EObject model) {
		if(model != null) {
			model.eAdapters().add(contentAdapter);
		}
	}
	
	private void unhookFromModel(EObject model) {
		if(model != null) {
			model.eAdapters().remove(contentAdapter);
		}
	}
	
	@Override
	public void dispose() {
		unhookFromModel(getEModel());
		super.dispose();
	}
	
	@Override
	public void init(IPageSite pageSite) {
		super.init(pageSite);
		hookIntoModel(getEModel());
		initPage();
	}

	//esplicitare la creazione dei vari contributor magari
	protected abstract void initPage();

	public void setModel(Object roster) {
		this.model = roster;
		
	}
	
	private EObject getEModel(){
		if (model instanceof EObject){
			return (EObject)model;
		}
		return null;
	}

}
